﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 武学列表面板
/// </summary>
public class WuxueListPanel : MonoBehaviour {

    private List<PersonageWuxue> Wuxues;
    private WuxueItem WuxueItemPrefab;

    // Use this for initialization
    void Start () {
		this.WuxueItemPrefab = Resources.Load<WuxueItem>("Prefabs/WuxueItem");
        Personage player = GlobalData.Instance.GetPlayerPersonage();
        this.Refresh(player.OwnWuxues);
    }
	
	// Update is called once per frame
	void Update () {
		
	}

    /// <summary>
    /// 根据数据刷新显示
    /// </summary>
    /// <param name="wuxues"></param>
    public void Refresh(List<PersonageWuxue> wuxues) {
        if (!this.IsEqual(wuxues, this.Wuxues)) { // 如果武学列表发生了变化，则更新数据与显示
            this.Wuxues = wuxues;
            this.UpdateUI();
        }
    }

    /// <summary>
    /// 更新ui
    /// </summary>
    private void UpdateUI() {
        this.ClearAllChildren();
        foreach (PersonageWuxue personageWuxue in this.Wuxues) {
            WuxueItem wuxueItem = GameObject.Instantiate<WuxueItem>(WuxueItemPrefab, transform, false);
            wuxueItem.Image.sprite = Resources.Load<Sprite>(personageWuxue.Wuxue.Sprite);
        }
    }

    /// <summary>
    /// 清空所有孩子
    /// </summary>
    private void ClearAllChildren() {
        for (int i = transform.childCount - 1; i >= 0; i--) {
            Destroy(transform.GetChild(i).gameObject);
        }
    }

    /// <summary>
    /// 两个武学列表是否相同
    /// </summary>
    /// <param name="list1"></param>
    /// <param name="list2"></param>
    /// <returns></returns>
    private bool IsEqual(List<PersonageWuxue> list1, List<PersonageWuxue> list2) {
        if (list1 == null || list2 == null) { // 其中一个为null
            return false;
        } else if (list1.Count != list2.Count) { // 总数不相等
            return false;
        } else { // 长度相同时，逐个比较
            bool isEqual = true;
            for (int i = 0; i < list1.Count; i++) {
                PersonageWuxue personageWuxue1 = list1[i];
                PersonageWuxue personageWuxue2 = list2[i];
                if (!personageWuxue1.WuxueId.Equals(personageWuxue2.WuxueId) || personageWuxue1.Grade != personageWuxue2.Grade) { // 比较id与等级
                    isEqual = false;
                    break;
                }
            }
            return isEqual;
        }
    }
}
